﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private Tag tag = new Tag(1, "aaaaa", "s=1;x=5;1",DataType.BOOL)
        {
            Drive = new ModbusRTU(1, "agv1", new SerialPort()
            {
                PortName = "COM1",
                BaudRate = 9600,
                Parity = Parity.None,
                DataBits = 8,
                StopBits = StopBits.One
            })
        };
        private Tag tag1 = new Tag(1, "aaaaa", "s=1;x=1;1",DataType.BOOL)
        {
            Drive = new ModbusRTU(1, "agv1", new SerialPort()
            {
                PortName = "COM1",
                BaudRate = 9600,
                Parity = Parity.None,
                DataBits = 8,
                StopBits = StopBits.One
            })
        };


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tag1.OnValueChanged += RefreshData;
        }

        private void RefreshData()
        {
            if (tag1.Value.Boolean == true)
            {
                textBox2.Text = 1.ToString();
            }
            else if (tag1.Value.Boolean == false)
            {
                textBox2.Text = 0.ToString();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            tag.Drive.Connect();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Storage storage = Storage.Empty;
            if (Convert.ToInt32(textBox1.Text) == 0)
            {
                
                storage.Boolean = false;
                tag.WriteTest(storage);
            }
            else if (Convert.ToInt32(textBox1.Text) == 1)
            {
                storage.Boolean = true;
                tag.WriteTest(storage);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            tag1.Drive.Connect();
            bool value = tag1.Read(tag1.Address).Content.Boolean;
            if (value == true)
            {
                textBox2.Text = 1.ToString();
            }
            else if (value == false)
            {
                textBox2.Text = 0.ToString();
            }
        }
    }
}
